#include <cstdlib>
#include <stdexcept>
#include <fstream>
#include <sstream>
#include <vector>
#include <fmt/format.h>
#include "minigrep.hpp"

Config parse_config(int argc, char* argv[]) {
    if(argc < 3) {
       throw std::runtime_error("Usage: minigrep --file <filename> --query <query_string> [--ignore-case]");
    }
    Config config = {nullptr, nullptr, false};
    config.file_name = argv[1];
    config.qurey_string = argv[2];
    bool ignore_case = false;
    const char* env_val=std::getenv("IGNORE_CASE");
    if(env_val&& std::string(env_val)=="1") {
        ignore_case = true;
    }
    return config;
}

std::string read_file(const  char* & file_name) {
    std::ifstream file(file_name);
    if (!file) {
        throw std::runtime_error("Could not open file: " + std::string(file_name));
    }
    // Read the entire file into a string
    return std::string((std::istreambuf_iterator<char>(file)),
                        std::istreambuf_iterator<char>());
}

std::vector<std::string> search(const std::string& query, const std::string& contents) {
    std::vector<std::string> results;
    std::istringstream stream(contents);
    std::string line;
    while (std::getline(stream, line)) {
        // Check if the line contains the query string
        if (line.find(query) != std::string::npos) {
            results.push_back(line);
        }
    
    }
    return results;
}


std::vector<std::string> search_case_insensitive(const std::string& query, const std::string& contents) {
    std::vector<std::string> results;
    std::istringstream stream(contents);
    std::string line;
    std::string lower_query = query;
    std::transform(lower_query.begin(), lower_query.end(), lower_query.begin(), ::tolower);
    
    while (std::getline(stream, line)) {
        std::string lower_line = line;
        std::transform(lower_line.begin(), lower_line.end(), lower_line.begin(), ::tolower);
        // Check if the line contains the query string
        if (lower_line.find(lower_query) != std::string::npos) {
            results.push_back(line);
        }
    }
    return results;
}

void run(Config &config) {
    std::string contents = read_file(config.file_name);
    std::vector<std::string> results;
    
    if (config.ignore_case) {
        results = search_case_insensitive(config.qurey_string, contents);
    } else {
        results = search(config.qurey_string, contents);
    }
    
    for (const auto& line : results) {
        fmt::print("{}\n", line);
    }
}

